package com.cqndt.disaster.device.common.config;

import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.cqndt.disaster.device.common.interceptor.LoginInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
   
	/**
     * @param corsRegistry
     * @return Cors（跨域请求）配置
     **/
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")   //   /**代表所有路径
                    .allowedOrigins("*")    //允许访问的客户端域名，若为*，则表示从任意域都能访问，即不受任何限制
                    .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")//允许访问的方法名
                    .allowCredentials(true)//表示是否允许发送cookie，当设置为true时，客户端的ajax请求，也需要将withCredentials设置为true
                    .maxAge(3600);//表示在3600秒内不需要再发送检验请求
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	LoginInterceptor interceptor = new LoginInterceptor();
    	InterceptorRegistration ir=registry.addInterceptor(interceptor);
    	ir.addPathPatterns("/login"); 
    }
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        //生成json时，将所有Long转换成String
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, jackson2HttpMessageConverter);
    }
}